import { useRef, useState, useMemo } from "react";
import styles from "./index.module.less";
import { message, Flex } from "antd";
import useUrl from "@/hooks/useUrl";
import { RESULT_CODES } from "@/api/helper/ResultCode";
import Loading from "@/components/Loading";
import { useRequest } from "ahooks";
import { useEffect } from "react";
import AMap from "@/components/AMap";
import { Descriptions } from "antd";
import cs from "classnames";
import { getTableColumns, getCreateColumns } from "./constant";
import { getCarDetail, createTaskByCar } from "@/api/modules/device";
import CreateForm from "@/components/CreateForm";
import { getDictByCode } from "@/api/modules/dict";
import { getLineList } from "@/api/modules/line";
import SuperTable from "@/components/SuperTable";
import { map, filter } from "lodash";
import { isValidLngLatArray, yawToAngle } from "@/utils/utils";
import useWebSocket from "@/store/hooks/useWebSocket";
import { PageContainer } from "@ant-design/pro-layout";
import { createVehicleInfoContent, createMarkerInfoContent, createVehicleInfoWindowConfig, createMarkerInfoWindowConfig } from '@/utils/infoWindowUtils';

export default () => {
	const { navigate, query } = useUrl();
	const detailId = query.get("detailId");
	const vinCode = query.get("vin");
	const createFormRef = useRef(null);

	const [detailInfo, setDetailInfo] = useState<any>({});
	const [jobList, setJobList] = useState([]);
	const [loopMarker, setLoopMarker] = useState([]); //接驳点位列表
	const [realTimePoint, setRealTimePoint] = useState<any>(null); //车辆实时位置
	const [realTimeData, setRealTimeData] = useState<any>(null); //车辆实时数据
	const [rectList, setRectList] = useState<any>([]);
	const [defaultValues] = useState(null);

	const { loading: loadingDetail, runAsync: getDetailAsync } = useRequest(getCarDetail, { manual: true });
	const { data: data1 } = useRequest(() => getDictByCode({ parentId: 0, code: "JOB_TYPE" }));
	const { data: data2 } = useRequest(() => getLineList({ page: { pageNum: 1, pageSize: 100 } }));
	const { data: data3 } = useRequest(() => getDictByCode({ parentId: 0, code: "POINT_TYPE" }));
	const taskTypeList = data1?.data;
	const loopList = data2?.data?.list;
	const pointTypeList = data3?.data;

	useWebSocket({
		url: `wss://software.hugesuccess.cn/ws/realtime/${vinCode}`,
		onMessage: data => {
			// console.log('Received data:', data);
			const result = data?.data;
			

			setRealTimePoint({
				position: [result?.longitude, result?.latitude], // [longitude, latitude]
				title: "车辆实时位置",
				icon: "/images/icon-map-car.png", // custom icon URL
				hoverText: "车辆实时位置",
				angle: yawToAngle(result?.yaw, "deg"),
				// 添加车辆基本信息
				vehicleInfo: {
					plateNo: detailInfo?.plateNo,
					vin: vinCode,
					vehicleType: detailInfo?.vehType,
					soc: result?.soc,
					speed: result?.speed,
					yaw: result?.yaw,
					vehicleStatus: result?.vehicleStatus,
					taskStatus: result?.taskStatus,
					anomalousStatus: result?.anomalousStatus
				},
				// 配置信息窗口
				infoWindow: createVehicleInfoWindowConfig({
					plateNo: detailInfo?.plateNo,
					vin: vinCode,
					vehicleType: detailInfo?.vehType,
					soc: result?.soc,
					speed: result?.speed,
					yaw: result?.yaw,
					vehicleStatus: result?.vehicleStatus,
					taskStatus: result?.taskStatus,
					anomalousStatus: result?.anomalousStatus
				})
			});
			setRealTimeData(result);
		}
	});

	// 监听字典数据变化，当字典加载完成后获取详情数据
	useEffect(() => {
		if (!detailId || !pointTypeList) return;
		handleGetDetail();
	}, [detailId, pointTypeList]);

	const handleGetDetail = () => {
		getDetailAsync({ id: detailId }).then((res: any) => {
			if (res?.code === RESULT_CODES.SUCCESS) {
				const data = res?.data ?? {};
				setDetailInfo(data?.vehicleInfo);
				setJobList(data?.jobList);

				setLoopMarker(
					map(data?.siteList, (item: any) => {
						const positionArr = item.lonLat?.split(",");
						
						return { 
							position: [positionArr[0], positionArr[1]],
							title: item?.name || '接驳点',
							icon: '/images/icon-joint.png',
							// 添加标记基本信息
							markerInfo: {
								name: item?.name,
								type: item?.type,
								callName: item?.callName,
								callPhone: item?.callPhone
							},
							// 配置信息窗口
							infoWindow: createMarkerInfoWindowConfig({
								name: item?.name,
								type: item?.type,
								callName: item?.callName,
								callPhone: item?.callPhone
							}, pointTypeList)
						};
					})
				);
				const rects = map(data?.sceneList, (item:any) => {
					const jsonParseResult = JSON.parse(item?.points)
					if (!isValidLngLatArray(jsonParseResult)) {
						return null
					}
					return {
						path: jsonParseResult
					}
				})
				const result = filter(rects, (item: any) => item !== null)
				setRectList(result);
			}
		});
	}
	
	const view = {
		label: "查看",
		value: "view"
	}

	const newColumns = [
		...getTableColumns({taskTypeList}),
		{
			title: "操作",
			width: 80,
			fixed: "right",
			dataIndex: "action-render",
			onClick: (key: string, record: any) => {
				switch (key) {
					case "view":
						navigate(`/task/list/detail?detailId=${record.id}`, { state: record });
						break;
				}
			},
			options: (record: any) => {
				return [view];
			}
		}
	];
	
	const CREATE_COLUMNS = useMemo(() => {
		return getCreateColumns({taskTypeList, loopList});
	}, [taskTypeList, loopList]);


	const handleCreate = (formData: any) => {
		createTaskByCar({...formData, vehId: detailId}).then((res: any) => {
			if(res.code === 200) {
				message.success("任务创建成功~");
				createFormRef?.current?.closeModel();
				handleGetDetail();
			}
		})
	}

	const handleCreateTask = () => {
		createFormRef?.current?.showModel();
	}

	// 格式化数值显示
	const formatValue = (value: any) => {
		if (value === undefined || value === null) return "-";
		return parseFloat(Number(value).toFixed(2));
	};

	// 格式化状态显示
	const formatStatus = (value: any, type: string) => {
		if (value === undefined || value === null) return "-";
		switch (type) {
			case "vehicleStatus":
				return value === 1 ? "在线" : "离线";
			case "taskStatus":
				return value === 1 ? "作业中" : "空闲";
			case "anomalousStatus":
				return value === 1 ? "有故障" : "正常";
			default:
				return value;
		}
	};

	return (
		<PageContainer
			title=" "
			breadcrumb={{
				routes: [
					{ href: "/device/car", breadcrumbName: "车辆管理" },
					{ href: "", breadcrumbName: "车辆详情" }
				]
			}}
		>
			<CreateForm
				title={"创建任务"}
				columns={CREATE_COLUMNS}
				onCreate={handleCreate}
				ref={createFormRef}
				defaultValues={defaultValues}
			>
				<></>
			</CreateForm>
			<Loading isHeight100 loading={loadingDetail}>
				<div className={cs(styles.detailContainer, "detailContainer")}>
					<div className={styles.container}>
						<div className={styles.content_wrap}>
							<div className={styles.content}>
								<div className={styles.moduleTitle}>基本信息</div>
								<Descriptions title="" column={1} labelStyle={{ width: "100px" }}>
									<Descriptions.Item label="车辆编号">{detailInfo?.id}</Descriptions.Item>
									<Descriptions.Item label="车牌号">{detailInfo?.plateNo}</Descriptions.Item>
									<Descriptions.Item label="供应商">{detailInfo?.supplier}</Descriptions.Item>
									<Descriptions.Item label="VIN码">{detailInfo?.vin}</Descriptions.Item>
									<Descriptions.Item label="车辆状态">{detailInfo?.status ?? "-"}</Descriptions.Item>
									<Descriptions.Item label="后续任务数">{detailInfo?.waitTaskCounts}</Descriptions.Item>
									<Descriptions.Item label="备注">{detailInfo?.remark}</Descriptions.Item>
								</Descriptions>
							</div>
						</div>
						<div className={cs(styles.content_wrap, styles.mt_20)}>
							<div className={styles.content}>
								<div className={styles.moduleTitle}>
									<div className={styles.title}>车辆任务信息</div>
									<div className={styles.btn} onClick={handleCreateTask}>
										创建任务
									</div>
								</div>
								<SuperTable className={cs([styles.tableContainer])} columns={newColumns} dataSource={jobList} rowKey={"id"} />
							</div>
						</div>
						<Flex justify="right" className={styles.btns}>
							<></>
						</Flex>
					</div>
					<div className={styles.mapBox}>
						<div className={styles.moduleTitle}>地图预览</div>
						<div className={styles.mapOuter}>
							<AMap markers={loopMarker} polygons={rectList} realTimeMaker={realTimePoint} />
						</div>
					</div>
				</div>
			</Loading>
		</PageContainer>
	);
};
